package com.swxc.smartorder.ui.activity

import android.content.IntentFilter
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import cn.jpush.android.api.JPushInterface
import com.google.gson.reflect.TypeToken
import com.jaeger.library.StatusBarUtil
import com.lzy.okgo.model.HttpParams
import com.swxc.smartorder.R
import com.swxc.smartorder.adapter.AdapterWork
import com.swxc.smartorder.app.ConfigSPS
import com.swxc.smartorder.app.GlobalAPI
import com.swxc.smartorder.broadcast.LocalBroadcastManager
import com.swxc.smartorder.broadcast.NetworkChange
import com.swxc.smartorder.entity.*
import com.swxc.smartorder.event.EventUtil
import com.swxc.smartorder.event.SimpleEvent
import com.swxc.smartorder.helper.TagAliasOperatorHelper
import com.swxc.smartorder.helper.TagAliasOperatorHelper.ACTION_SET
import com.swxc.smartorder.helper.TagAliasOperatorHelper.sequence
import com.swxc.smartorder.network.NetworkHelper
import com.swxc.smartorder.receiver.MyPushMessageReceiver
import com.swxc.smartorder.ui.base.BaseActivity
import com.swxc.smartorder.ui.dialog.NoNetworkDialog
import com.swxc.smartorder.utils.AppSharePreferenceMgr
import com.swxc.smartorder.utils.JsonUtil
import com.swxc.smartorder.utils.PushUtils
import kotlinx.android.synthetic.main.activity_work.*
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.LinkedHashSet
import kotlin.collections.ArrayList

class WorkActivity : BaseActivity(), View.OnClickListener {

    companion object {
        private const val INTERVAL_TIME = 2000
        const val KEY_TITLE = "title"
        const val KEY_MESSAGE = "message"
        const val KEY_EXTRAS = "extras"
        const val MESSAGE_RECEIVED_ACTION = " com.swxc.smartorder.MESSAGE_RECEIVED_ACTION"
    }


    var isForegrounds = false
    private var exitTime: Long = 0
    private var mNetworkHelper: NetworkHelper? = null
    private var mList: MutableList<OrderBean>? = null
    private var mAdapter: AdapterWork? = null

    private var networkIsConnect = true
    private var mNoNetworkDialog: NoNetworkDialog? = null
    private var statusLayoutManager: StatusLayoutManager? = null

    private var mMessagePushMessageReceiver: MyPushMessageReceiver? = null

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_menu -> {
                readyGo(InformationActivity::class.java)
            }
            R.id.iv_order -> {
                readyGo(OrderActivity::class.java)
            }
        }
    }


    fun isForeground(): Boolean {
        return isForegrounds
    }

    override fun onRestart() {

        super.onRestart()
        isForegrounds = true
    }

    override fun onStop() {
        super.onStop()
        isForegrounds = false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_work)
        EventUtil.getInstance().register(this)
        StatusBarUtil.setColor(this, resources.getColor(R.color.colorPrimary), 0)
        mNetworkHelper = NetworkHelper(mContext, supportFragmentManager)
        initViewAndEvent()
        initData()

        setJpushTag()
        setJpushRegistrationId()
        registerMessageReceiver()


    }

    private fun setJpushRegistrationId() {

        val registrationId = AppSharePreferenceMgr.get(mContext, ConfigSPS.REGISTRATION_ID, "") as String
        Log.e(BUG_TAG, registrationId)
        val alisaParams = HttpParams()
        alisaParams.put("pushAlias", registrationId)
        mNetworkHelper?.putRequest(GlobalAPI.setAlisa, alisaParams, object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {
                Log.e(BUG_TAG, "设置Alias${json}")
            }

            override fun requestFail() {
            }
        })


    }

    /**
     * 设置极光推送Tag
     */
    private fun setJpushTag() {
        var tags: Set<String>? = null
        var action = -1
        val tag = AppSharePreferenceMgr.get(mContext, ConfigSPS.PUSH_TAG, "") as String

        if (tag == null || tag.isEmpty()) {
            return
        } else {
            tags = getInPutTags()
        }
        action = ACTION_SET
        val tagAliasBean = TagAliasBean()
        tagAliasBean.action = action
        tagAliasBean.tags = tags!!
        tagAliasBean.isAliasAction = false
        TagAliasOperatorHelper.getInstance().handleAction(applicationContext, sequence, tagAliasBean)


    }


    /**
     * 获取输入的tags
     */
    private fun getInPutTags(): Set<String>? {
        val tag = AppSharePreferenceMgr.get(mContext, ConfigSPS.PUSH_TAG, "") as String
        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {
            Log.e(BUG_TAG, "tag无效")
            return null
        }

        // ","隔开的多个 转换成 Set
        val sArray = tag.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        val tagSet = LinkedHashSet<String>()
        for (sTagItme in sArray) {
            if (!PushUtils.isValidTagAndAlias(sTagItme)) {
                Log.e(BUG_TAG, "tag无效")
                return null
            }
            tagSet.add(sTagItme)
        }
        if (tagSet.isEmpty()) {
            Log.e(BUG_TAG, "tag不能为空")
            return null
        }
        return tagSet
    }

    private fun registerMessageReceiver() {
        mMessagePushMessageReceiver = MyPushMessageReceiver()
        val filter = IntentFilter()
        filter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY
        filter.addAction(MESSAGE_RECEIVED_ACTION)
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessagePushMessageReceiver, filter)


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType == SimpleEvent.NETWORK_CHANGE) {


            when (simpleEvent.mEventValue) {
                NetworkChange.NETWORK_CONNECT, NetworkChange.WIFI_CONNECT -> {
                    layout_without_network.visibility = View.GONE
                    networkIsConnect = true
                }
                NetworkChange.WITHOUT_NETWORK -> {
                    layout_without_network.visibility = View.VISIBLE
                    networkIsConnect = false

                }
            }

        } else if (simpleEvent.mEventType == SimpleEvent.REGISTRATION_ID) {

            when (simpleEvent.mEventValue) {
                0x0001 -> {

                }
            }
        } else {
            return
        }
    }

    private fun initData() {
        val httpParams = HttpParams()
        httpParams.put("fields", "id,status,title,createTime,priorityLevel,timeout")
        mNetworkHelper?.getRequest(GlobalAPI.workList, httpParams, object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {
                if (refreshLayout.isRefreshing) {
                    refreshLayout.finishRefresh()
                }
                val type = object : TypeToken<CommonDataList<OrderBean>>() {}.type
                val fromJson = JsonUtil.fromJson<CommonDataList<OrderBean>>(json, type) ?: return
                if (fromJson.success) {
                    if (fromJson.data.isEmpty()) {
                        statusLayoutManager?.showEmptyLayout()
                    } else {
                        statusLayoutManager?.showSuccessLayout()
                        mList?.addAll(fromJson.data)
                        mAdapter?.notifyDataSetChanged()
                    }
                } else {
                    when (fromJson.responseCode) {
                        1018 -> {
                            mNetworkHelper?.refreshToken(GlobalAPI.login, object : NetworkHelper.NetWorkHelperBack {
                                override fun requestSuccess(json: String) {
                                    val type = object : TypeToken<CommonData<TokenData>>() {}.type
                                    val fromJson = JsonUtil.fromJson<CommonData<TokenData>>(json, type)
                                            ?: return
                                    if (fromJson.success) {
                                        AppSharePreferenceMgr.put(mContext, ConfigSPS.TOKEN, fromJson.data.accessToken)
                                        AppSharePreferenceMgr.put(mContext, ConfigSPS.REFRESH_TOKEN, fromJson.data.refreshToken)
                                        initData()
                                    } else {
                                        readyGoThenKill(LoginActivity::class.java)
                                    }

                                }

                                override fun requestFail() {
                                    readyGoThenKill(LoginActivity::class.java)
                                }
                            })

                        }
                    }
                }
            }

            override fun requestFail() {
                if (refreshLayout.isRefreshing) {
                    refreshLayout.finishRefresh()

                }
                statusLayoutManager?.showErrorLayout()
            }
        })


    }

    private fun initViewAndEvent() {

        mNoNetworkDialog = NoNetworkDialog()
        val emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty, null, false)

        emptyView.findViewById<TextView>(R.id.tv_empty).text = "太好啦~\n老板没有安排工作！"
        emptyView.findViewById<TextView>(R.id.tv_refresh).setOnClickListener { initData() }

        JPushInterface.init(applicationContext)
        mList = ArrayList()
        mAdapter = AdapterWork(mList)
        rv_work.layoutManager = LinearLayoutManager(this)
        rv_work.adapter = mAdapter


        iv_menu.setOnClickListener(this)
        iv_order.setOnClickListener(this)

        mAdapter?.setOnItemClickListener { adapter, _, position ->


            if (networkIsConnect) {
                val item: OrderBean = adapter.data[position] as OrderBean
                val bundle = Bundle()
                bundle.putLong("orderID", item.id)
                readyGo(OrderDetailActivity::class.java, bundle)
            } else {
                readyGo(WithoutNetWorkActivity::class.java)
            }
        }

        refreshLayout.setOnRefreshListener {
            mList?.clear()
            mAdapter?.notifyDataSetChanged()
            initData()

        }

        statusLayoutManager = StatusLayoutManager.Builder(refreshLayout)
                .setEmptyLayout(emptyView)
                .setErrorLayout(R.layout.layout_error)
                .setOnStatusChildClickListener(object : OnStatusChildClickListener {
                    override fun onErrorChildClick(p0: View?) {
                        initData()
                    }

                    override fun onEmptyChildClick(p0: View?) {
                    }

                    override fun onCustomerChildClick(p0: View?) {
                    }
                })
                .build()

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun exit() {
        if (System.currentTimeMillis() - exitTime > INTERVAL_TIME) {
            Toast.makeText(applicationContext, "再按一次退出程序",
                    Toast.LENGTH_SHORT).show()
            exitTime = System.currentTimeMillis()
        } else {
            System.exit(0)
        }


    }

    override fun onDestroy() {
        EventUtil.getInstance().unregister(this)
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessagePushMessageReceiver)
        super.onDestroy()
    }
}
